let _token = $('input[name=_token]').eq(0).val()
let uploadedImageType = 'image/jpeg'
let $image = $('#image')
  ; (function ($, global) { // 图片裁剪功能封装
    let URL = global.URL || global.webkitURL
    let Cropper = global.Cropper
    let $file = $('input[name=img]')
    let $up = $('input[name=up]')
    let $aspect = $('input[name=aspect_ratio]')
    let $cropperGroup = $('.form-cropper')
    let $cropperControl = $('.form-cropper-control')
    let $cropperPreview = $('.form-preview')
    let $originGroup = $('.form-origin')
    let $origin = $('#origin-img')
    let originalImageURL = $image.attr('src')
    let uploadedImageURL
    let $crop
    let minContainerWidth = 538

    let fnCropperReady = function () {
      fnStopLoading()
      fnCropScaleInit()
      $cropperGroup.show()
      $cropperControl.show()
      $cropperPreview.show()
      $originGroup.hide()
    }

    let options = {
      viewMode: 2,
      preview: '.img-preview',
      aspectRatio: 16 / 9,
      minContainerWidth: minContainerWidth,
      minContainerHeight: 1000,
      crop: function (e) { },
      ready: fnCropperReady
    }


    let fnCropperRemove = function () {
      $cropperGroup.hide()
      $cropperControl.hide()
      $cropperPreview.hide()
    }

    let fnCropper = function (f) {
      var files = f.files
      var file
      if (files && files.length) {
        file = files[0]
        if (/^image\/\w+$/.test(file.type)) {
          uploadedImageType = file.type
          if (uploadedImageURL) {
            URL.revokeObjectURL(uploadedImageURL)
          }
          uploadedImageURL = URL.createObjectURL(file)
          let flag = $('input[name=up]:checked').val()
          console.log(flag)
          if (flag == 1) {
            $image.cropper('destroy').attr('src', uploadedImageURL)
            $image[0].onload = function () {
              let width = this.width
              let height = this.height
              options.minContainerHeight = options.minContainerWidth * height / width
              $image.cropper(options)
            }
            global.cropimg = $image
          } else {
            $origin.cropper('destroy').attr('src', uploadedImageURL)
            $origin[0].onload = function () {
              let width = this.width
              let height = this.height
            }
            fnCropperRemove()
            $originGroup.show()
          }
        } else {
          layer.msg('Please choose an image file.')
        }
      }
    }

    let fnTrigger = function () {
      $file.change(function () {
        fnCropper(this)
      })

      $up.change(function () {
        let file = $file.val()
        if (file != '') {
          fnCropper($file[0])
        }
      })
    }
    let fnCropScaleInit = function () {
      global.scaleX = 1
      global.scaleY = 1
    }

    let fnAddFormInit = function () {
      $file.val('');
      $originGroup.hide()
      $cropperGroup.hide()
      $cropperControl.hide()
      $cropperPreview.hide()
      $image.cropper('destroy')
    }

    let fnReCropper = function () {
      let aspect_ratio = $aspect.val()
      if (aspect_ratio.indexOf('/') != -1) {
        num = aspect_ratio.split('/')
        if (!isNaN(num[0]) && !isNaN(num[1])) {
          aspect_ratio = num[0] / num[1]
          options.aspectRatio = aspect_ratio
        }
        else {
          options.aspectRatio = null
        }
      }
      else if (!isNaN(aspect_ratio)) {
        options.aspectRatio = aspect_ratio
      } else {
        options.aspectRatio = null
      }
      $image.cropper('destroy').cropper(options)
    }
    global.fnReCropper = fnReCropper
    global.fnAddFormInit = fnAddFormInit
    fnTrigger()
  })(jQuery, window)


  ; (function ($, global) {//图片添加.
    $modal = $("#album-add-modal")
    $form = $("#album-add-form")
    $submit = $modal.find("button.submit")

    let fnAddAlbum = function (data) {
      fnLoading()
      fnUploadAjax('POST', 'album/add', data, 'json', fnAddSuccess, fnError)
    }

    let fnAddSuccess = function (data) {
      layer.msg('新增成功')
      fnReload()
    }

    let fnError = function () {
      fnStopLoading()
    }

    let fnTrigger = function () {
      $submit.click(function () {
        let data = new FormData($form[0])
        if (data.get("up") == 1) {
          data.delete('img')
          try {
            imageData = $image.cropper('getCroppedCanvas').toBlob(function (blob) {
              data.append('img', blob)
              // let objData = {}
              // data.forEach((value, key) => {
              //   objData[key] = value;})
              // if (reqVerify(objData, verifyAdd)) {
              fnAddAlbum(data)
              // }
            }, uploadedImageType)
          } catch (e) {
            layer.msg('请选择图片')
          }
        } else {
          fnAddAlbum(data)
        }
      })
    }

    fnTrigger()
  })(jQuery, window)

  ; (function ($, global) {//图片删除
    let $deleteSpan = $('.album-delete-span')

    let fnDelSuccess = function (data) {
      layer.msg('删除成功', { icon: 1 })
      $('#album-' + data.id).fadeTo('slow', 0.01, function () { // fade
        $(this).slideUp('slow', function () { // slide up
          $(this).remove()
        })
      })
    }

    let fnDelError = function () { }

    let fnDelConfirm = function (data) {
      layer.confirm('确定删除此项？', {
        btn: ['确定', '取消'] // 按钮
      }, function () {
        fnLoading()
        fnDelAlbum(data)
      }, function () { })
    }

    let fnDelAlbum = function (data) {
      fnApiAjax('POST', 'album/del', data, 'json', fnDelSuccess, fnDelError)
    }

    let fnTrigger = function () {
      $deleteSpan.click(function () {
        $this = $(this)
        let id = $this.attr('data-id')
        let data = {
          id: id,
          s: 1,
          _token: _token
        }
        fnDelConfirm(data)
      })
    }
    fnTrigger()
  })(jQuery, window)

  ; (function ($, global) {//图片编辑
    let $modal = $("#album-edit-modal");
    let $form = $modal.find("#album-edit-form")
    let $editSpan = $('.album-edit-span')
    let $submit = $modal.find("button.submit")

    let fnEditFormInit = function ($span, $form) {
      $form.find('input[name=id]').val($span.attr('data-id'))
      $form.find('input[name=title]').val($span.attr('data-title'))
      $form.find('input[name=description]').val($span.attr('data-description'))
      $form.find('input[name=rank]').val($span.attr('data-rank'))
      let status = $span.attr('data-status')
      $form.find("input[name='status'][value='" + status + "']").prop('checked', 'checked')
      $form.find('img.img').attr('src', $span.attr('data-pic')).attr('alt', $span.attr('data-title')).attr('title', $span.attr('data-title'))
      $form.find('input[name=path]').val($span.attr('data-path'))
    }

    let fnInitEditReq = function ($form) {
      return {
        _token: _token,
        id: $form.find('input[name=id]').val(),
        title: $form.find('input[name=title]').val(),
        intro: $form.find('input[name=description]').val(),
        rank: $form.find('input[name=rank]').val(),
        status: $form.find('input[name=status]:checked').val()
      }
    }

    let fnEditAjax = function (data) {
      fnApiAjax('POST', 'album/edit?id=' + data.id, data, 'json', fnCommonEditSuccess, fnCommonEditError)
    }

    let fnTrigger = function () {
      $editSpan.click(function () {
        $this = $(this)
        fnEditFormInit($this, $form)
      })

      $submit.click(function () {
        let req = fnInitEditReq($form)

        fnBtnDisable($(this))
        fnLoading()
        fnEditAjax(req)

      })
    }

    fnTrigger()
  })(jQuery, window)